package com.netafull.db;


import java.util.ArrayList;
import java.util.List;

import com.netafull.analyze.Category;
import com.netafull.analyze.CategoryCount;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CategoryService {

	DBHelper helper = null;
	public CategoryService(Context context) {
		helper = new DBHelper(context);
	}

	public void save(Category category) {
		SQLiteDatabase db = helper.getWritableDatabase();
		db.execSQL("insert into mtb_category(id,category_name,title_count,img_flag) values (?,?,?,?)", new Object[]{category.getId(),category.getCategory_name(),category.getTitle_count(),category.getImg_flag()});
		db.close();
	}
	public Cursor getData(){
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor c = db.rawQuery("select * from mtb_category",null);
		
		return c;
	}
	public void save(List<Category> list){
		for (Category category : list) {
			this.save(category);
		}
	}
	public List<Category> getAll(){
		List<Category> all = new ArrayList<Category>();
		Cursor cursor = this.getData();
		while(cursor.moveToNext()){
			all.add(new Category(cursor.getInt(1),cursor.getString(2),cursor.getInt(3),cursor.getInt(4)));
		}
		cursor.close();
		return all;
	}
	public int getCount(){
		String sql = "select * from mtb_category";
		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery(sql, null);
		if(cursor.moveToNext()){
			int temp = (int) cursor.getLong(0);
			cursor.close();
			db.close();
			return temp;
		}
		return 0;
	}
	public void update(List<Category> list){
		SQLiteDatabase db = helper.getWritableDatabase();
		db.execSQL("drop table if exists mtb_category");
		String sql = "create table mtb_category(_id integer primary key autoincrement,id integer,category_name varchar(255),title_count integer,img_flag integer)";
		db.execSQL(sql);
		db.close();
		save(list);
	}
	public void updateCount(CategoryCount count) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("title_count", count.getCount());
		db.update("mtb_category", values, "id=?", new String[]{String.valueOf(count.getCategory())});
		db.close();
	}
}
